package controllers

import (
	"chat/models"
	"chat/pkg/util"
	"chat/response"
	"chat/services"
	"fmt"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

func GetUserInfo(c *gin.Context) {
	s := c.Query("id")
	if s == "" {
		fmt.Printf("get Param failed")
		c.JSON(200, response.NewResponse(
			200,
			"id can not found",
			nil,
		))
		return
	}

	oi, err := primitive.ObjectIDFromHex(s)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		c.JSON(200, response.NewResponse(
			200,
			err.Error(),
			nil,
		))
		return
	}

	var user models.User
	user.Id = oi
	err = services.GetUserInfo(&user)
	if err != nil {
		c.JSON(200, response.NewResponse(
			200,
			err.Error(),
			nil,
		))
		return
	}

	c.JSON(200, response.NewResponse(
		200,
		"OK",
		response.NewUserResp(&user),
	))
}

func Register(c *gin.Context) {
	var user models.User
	user.UserName = c.PostForm("username")
	user.PassWord = c.PostForm("password")

	err := services.Register(&user)
	if err != nil {
		c.JSON(200, response.NewResponse(
			2,
			err.Error(),
			nil,
		))
		return
	}

	c.JSON(200, response.NewResponse(
		200,
		"success",
		nil,
	))

}

func Login(c *gin.Context) {
	var user models.User
	user.UserName = c.PostForm("username")
	user.PassWord = c.PostForm("password")

	err := services.Login(&user)

	if err != nil {
		// 2 表示用户名或密码错误
		c.JSON(200, response.NewResponse(
			2,
			err.Error(),
			nil,
		))
		return
	}

	s, err := util.GenerateToken(user.UserName)
	if err != nil {
		c.JSON(200, response.NewResponse(
			3,
			err.Error(),
			nil,
		))
		return
	}

	var token response.LoginReq
	token.Token = s
	c.JSON(200, response.NewResponse(
		200,
		"OK",
		token,
	))
	return
}
